<?php

namespace app\api\controller;

use app\admin\model\Setting;
use app\admin\model\user\Extend;
use app\common\model\Third;
use Carbon\Carbon;
use EasyWeChat\Factory;
use fast\Random;
use fast\Http;
use think\Env;
use think\Exception;
use think\Hook;

// part-time
class Login extends \app\common\controller\Api
{
    protected $noNeedLogin = ['*'];

    public function mpWeixinLogin()
    {
        if ($this->request->isPost()) {
            $code = $this->request->post('code', '');

            $mpAppid = Env::get('mp.appid');
            $mpAppSecret = Env::get('mp.app_secret');

            $config = [
                'app_id' => $mpAppid,
                'secret' => $mpAppSecret,

                'response_type' => 'array',
                'log' => [
                    'level' => 'debug',
                    'file' => ROOT_PATH . '/runtime/log/wechat.log',
                ],
            ];

            try {

                $app = Factory::miniProgram($config);

                $res = $app->auth->session($code);

                if (!isset($res['session_key'])) {
                    throw new Exception('session_key 未得到');
                }
                $sessionKey = $res['session_key'];
                $openid = $res['openid'];

            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }

            //是否通过微信登录过
            $thirdUser = Third::where('openid', $openid)->where('platform', Third::PLATFORM_MP_WEIXIN)->find();

            if (is_null($thirdUser)) {
                $this->result('未注册用户', null, 2);
            } else {
                $user = \app\common\model\User::get($thirdUser->user_id);

                // 更新微信的sessionkey
                $thirdUser->sessionkey = $sessionKey;
                $thirdUser->save();

                // 登录
                if ($user->status != 'normal') {
                    $this->error('账号被锁，请联系管理员');
                }
                //如果已经有账号则直接登录
                $this->auth->keeptime(0);
                $ret = $this->auth->direct($user->id);
            }

            if ($ret) {
                $this->auth->setAllowFields(['id', 'username', 'nickname', 'mobile', 'avatar', 'score', 'gender', 'birthday']);
                $userinfo = $this->auth->getUserinfo();
                $userinfo['avatar'] = ykxImageUrl($userinfo['avatar']);

                $data = ['userinfo' => $userinfo];
                $this->success('登录成功', $data);
            } else {
                $this->error($this->auth->getError());
            }
        }
        $this->error('need post request');
    }

    public function mpWeixinRegisterAndLogin()
    {
        if ($this->request->isPost()) {
            $code = $this->request->post('code', '');
            $nickName = $this->request->post('nickname', '微信用户_' . Random::alnum(6));
            $avatar = $this->request->post('avatar', '/assets/img/avatar.png'); ;
            $phone = $this->request->post('phone', '');
            $gender = 0;
            if (empty($phone)) {
                $this->error('手机号未获取');
            }
            if (empty($code) or empty($nickName)) {
                $this->error('参数不完整');
            }

            $mpAppid = Env::get('mp.appid');
            $mpAppSecret = Env::get('mp.app_secret');

            $config = [
                'app_id' => $mpAppid,
                'secret' => $mpAppSecret,

                'response_type' => 'array',
                'log' => [
                    'level' => 'debug',
                    'file' => ROOT_PATH . '/runtime/log/wechat.log',
                ],
            ];

            try {
                $app = Factory::miniProgram($config);

                $res = $app->auth->session($code);
                if (!isset($res['session_key'])) {
                    throw new Exception('session_key 未得到');
                }
                $sessionKey = $res['session_key'];
                $openid = $res['openid'];

            } catch (\Exception $e) {

                $this->error($e->getMessage());
            }

            // 注册和登录
            $thirdUser = Third::where('openid', $openid)->where('platform', Third::PLATFORM_MP_WEIXIN)->find();
            // 注册
            if (is_null($thirdUser)) {
                Hook::add('user_register_successed', function ($param) use ($openid, $nickName, $avatar, $gender, $phone, $sessionKey) {
                    Third::create([
                        'user_id' => $param->id,
                        'platform' => Third::PLATFORM_MP_WEIXIN,
                        'openid' => $openid,
                        'openname' => $nickName,
                        'sessionkey' => $sessionKey,
                    ]);
                    $param->nickname = $nickName;
                    $param->avatar = $avatar;
                    $param->gender = $gender;
                    $param->mobile = $phone;
                    $param->save();

                });
                $ret = $this->auth->register(Third::PLATFORM_MP_WEIXIN . Random::alnum(), Random::alnum());
            } else {
                $user = \app\common\model\User::get($thirdUser->user_id);

                // 更新微信的sessionkey
                $thirdUser->sessionkey = $sessionKey;
                $thirdUser->save();

                // 登录
                if ($user->status != 'normal') {
                    $this->error('账号被锁，请联系管理员');
                }
                //如果已经有账号则直接登录
                $this->auth->keeptime(0);
                $ret = $this->auth->direct($thirdUser->user_id);
            }

            if ($ret) {
                $this->auth->setAllowFields(['id', 'username', 'nickname', 'mobile', 'avatar', 'score', 'gender', 'birthday']);
                $userinfo = $this->auth->getUserinfo();
                $userinfo['avatar'] = ykxImageUrl($userinfo['avatar']);

                $data = ['userinfo' => $userinfo];
                $this->success('登录成功', $data);
            } else {
                $this->error($this->auth->getError());
            }

        }
        $this->error('need post request');

    }

    public function mpWeixinGetPhone()
    {

        if ($this->request->isPost()) {

            $user = $this->auth->getUser();

            $code = $this->request->post('code');
            $doSet = $this->request->post('doSet', 0); //是否保存

            $mpAppid = Env::get('mp.appid');
            $mpAppSecret = Env::get('mp.app_secret');

            $config = [
                'app_id' => $mpAppid,
                'secret' => $mpAppSecret,

                'response_type' => 'array',
                'log' => [
                    'level' => 'debug',
                    'file' => ROOT_PATH . '/runtime/log/wechat.log',
                ],
            ];

            try {
                $app = Factory::miniProgram($config);
                $accessToken = $app->access_token->getToken()['access_token'];

                $url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=$accessToken";

                $headers = ['content-type:application/json'];
                $options = [
                    CURLOPT_HTTPHEADER => $headers
                ];

                $postdata = [
                    'code' => $code,
                ];

                $res = Http::post($url, json_encode($postdata), $options);
                $res = json_decode($res, true);
                if (0 == $res['errcode']) {
                    $phone = $res['phone_info']['phoneNumber'];
                } else {
                    throw new \Exception($res['errmsg']);
                }

                if ($doSet) {
                    $user->mobile = $phone;
                    $user->save();
                }

            } catch (\Exception $e) {

                $this->error($e->getMessage());
            }

            $this->success('ok', ['phone' => $phone]);
        }
    }
}
